"use client";
import "@ant-design/v5-patch-for-react-19";
import { useState, useRef, useEffect } from "react";
import { Input, Button, List, Spin, Empty, Flex, Tooltip, message } from "antd";
import {
  SendOutlined,
  UserOutlined,
  RobotOutlined,
  ArrowUpOutlined,
  XFilled,
  CopyOutlined,
} from "@ant-design/icons";
const { TextArea } = Input;
type Message = {
  id: string;
  role: "user" | "bot";
  text: string;
};

export default function ChatPage() {
  const [msg, setMsg] = useState("");
  const [list, setList] = useState<Message[]>([]);
  const [loading, setLoading] = useState(false);
  const bodyRef = useRef<HTMLDivElement>(null);
  // 自动滚动到底部
  useEffect(() => {
    bodyRef.current?.scrollTo({
      top: bodyRef.current.scrollHeight,
      behavior: "smooth",
    });
  }, [list]);

  // 发送消息
  const send = async () => {
    if (!msg.trim()) return;
    const userMsg: Message = {
      id: Date.now().toString(),
      role: "user",
      text: msg.trim(),
    };
    setList((prev) => [...prev, userMsg]);
    setMsg("");
    setLoading(true);

    try {
      // ===== 替换成你的真实接口 =====
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content: userMsg.text }),
      }).then((r) => r.json());

      const botMsg: Message = {
        id: (Date.now() + 1).toString(),
        role: "bot",
        text: res.reply,
      };
      setList((prev) => [...prev, botMsg]);
    } catch (e) {
      const errMsg: Message = {
        id: (Date.now() + 2).toString(),
        role: "bot",
        text: "服务异常，请重试",
      };
      setList((prev) => [...prev, errMsg]);
    } finally {
      setLoading(false);
    }
  };

  const [value, setValue] = useState("");
  const [tag, setTag] = useState(false);
  const [state, setState] = useState(false);
  const [tip, setTip] = useState("请先输入内容");
  const handleChange = (e: any) => {
    const val = e.target.value;
    if (val) {
      setTag(true);
      setTip("发送");
    } else {
      setTag(false);
      setTip("请先输入内容");
      setState(false);
    }

    setValue(val);
  };

  const sendClick = async () => {
    // setState(!state);
    // state ? setTip("发送") : setTip("停止");
    //  if (!msg.trim()) return;
    const userMsg: Message = {
      id: Date.now().toString(),
      role: "user",
      text: value.trim(),
    };
    setList((prev) => [...prev, userMsg]);
    setMsg("");
    setLoading(true);
    setValue("");
    try {
      const res = await fetch("http://117.72.204.113:28882/api/v1/process", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: value.trim() }),
      }).then((r) => r.json());
      // const res = await fetch("/api/chat", {
      //   method: "POST",
      //   headers: { "Content-Type": "application/json" },
      //   body: JSON.stringify({ content: userMsg.text }),
      // }).then((r) => r.json());
      // console.log(11111);
      // console.log(res);
      const botMsg: Message = {
        id: (Date.now() + 1).toString(),
        role: "bot",
        text: res.message,
      };
      setList((prev) => [...prev, botMsg]);
    } catch (e) {
      const errMsg: Message = {
        id: (Date.now() + 2).toString(),
        role: "bot",
        text: "服务异常，请重试",
      };
      setList((prev) => [...prev, errMsg]);
    } finally {
      // setTag(false);
      setLoading(false);
      // setTip("发送");
      // setState(false);
    }
  };

  const handlePressEnter = (e: any) => {
    if (e.key === "Enter" && e.shiftKey === false) {
      sendClick();
    }
  };
  const copyClick = async (text: string) => {
    const errText = "当前环境不支持复制，请手动选择文本复制。";
    const sucText = "已复制到剪贴板";
    try {
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(text);
        message.success(sucText);
        return;
      }
      const textarea = document.createElement("textarea");
      textarea.value = text;
      textarea.style.position = "fixed";
      textarea.style.opacity = "0";
      textarea.style.left = "-9999px";
      document.body.appendChild(textarea);
      textarea.select();
      const successful = document.execCommand("copy");
      document.body.removeChild(textarea);
      if (successful) {
        message.success(sucText);
      } else {
        throw new Error(errText);
      }
    } catch (err) {
      message.error(errText);
    }
  };

  return (
    <div className="flex flex-col h-screen">
      {/* 头部 */}
      <header className="bg-white px-4 py-3 text-lg font-semibold">
        数开智能问数
      </header>

      {/* 消息体 */}
      <main ref={bodyRef} className="flex-1 overflow-y-auto bg-gray-50 p-2 ">
        {list.length === 0 && (
          <Empty description="暂无消息" className="mt-20" />
        )}
        <List
          dataSource={list}
          split={false}
          locale={{ emptyText: " " }}
          renderItem={({ id, role, text }) => (
            <List.Item key={id} className="flex items-start mb-3">
              {role === "user" ? (
                <div className="ml-auto flex gap-2 max-w-[70%] items-center relative group cursor-pointer">
                  <div className="bg-blue-500 text-white rounded-xl px-3 py-2 break-words overflow-hidden cursor-pointer">
                    <div className="cursor-text"> {text}</div>
                  </div>
                  <div
                    className="text-sm text-gray-500 absolute -bottom-6 right-6 opacity-0 group-hover:opacity-100 !w-50px"
                    onClick={() => copyClick(text)}
                  >
                    <CopyOutlined /> <span>复制</span>
                  </div>
                  <UserOutlined className="text-blue-500 mt-1" />
                </div>
              ) : (
                <div className="flex items-start gap-2 max-w-[70%] relative group cursor-pointer">
                  <RobotOutlined className="text-green-600 mt-1" />
                  <div className="bg-white border rounded-xl px-3 py-2 break-words overflow-hidden">
                    <div className="cursor-text"> {text}</div>
                  </div>
                  <div
                    className="text-sm text-gray-500 absolute -bottom-6 left-6 opacity-0 group-hover:opacity-100 !w-50px"
                    onClick={() => copyClick(text)}
                  >
                    <CopyOutlined /> <span>复制</span>
                  </div>
                </div>
              )}
            </List.Item>
          )}
        />
        {loading && (
          <div className="flex items-center gap-2 text-gray-400">
            <Spin size="small" /> 正在输入...
          </div>
        )}
      </main>

      {/* 底部输入 */}
      <footer className="bg-white p-2 ">
        <div className="h-[100px] w-full px-2 border  border-gray-300 rounded-lg flex items-center">
          {/* <div> */}
          <TextArea
            value={value}
            variant="borderless"
            onChange={handleChange}
            placeholder="尽管问……"
            autoSize={{ minRows: 2, maxRows: 3 }}
            onPressEnter={handlePressEnter}
          />
          <Tooltip title={tip}>
            <Button
              onClick={sendClick}
              type="primary"
              shape="circle"
              disabled={!tag}
              loading={loading}
              icon={state ? <XFilled /> : <ArrowUpOutlined />}
            />
          </Tooltip>
          {/* <Flex gap="small" wrap>
              <Tooltip title="search">
                <Button type="primary">Primary Button</Button>
              </Tooltip>
              <Tooltip title="search">
                <Button type="primary">Primary Button</Button>
              </Tooltip>
            </Flex>
            <Flex gap="small" wrap>
              <Tooltip title={tip}>
                <Button
                  onClick={sendClick}
                  type="primary"
                  shape="circle"
                  disabled={!tag}
                  loading={loading}
                  icon={state ? <XFilled /> : <ArrowUpOutlined />}
                />
              </Tooltip>
            </Flex> */}
          {/* </div> */}
        </div>
        {/* <Input
          value={msg}
          onChange={(e) => setMsg(e.target.value)}
          placeholder="请输入消息"
          onPressEnter={send}
        />
        <Button type="primary" icon={<SendOutlined />} onClick={send} loading={loading}>
          发送
        </Button> */}
      </footer>
    </div>
  );
}
